package controllers

import (
	"fmt"
	"github.com/flaravel/quanlaolao/app/models/channel"
	"github.com/flaravel/quanlaolao/app/models/cps"
	"github.com/flaravel/quanlaolao/app/requests"
	"github.com/flaravel/quanlaolao/pkg/flash"
	"github.com/flaravel/quanlaolao/pkg/route"
	"github.com/flaravel/quanlaolao/pkg/types"
	"github.com/flaravel/quanlaolao/pkg/upload"
	"github.com/flaravel/quanlaolao/pkg/view"
	"net/http"
)

type CpsController struct {
	BaseController
}

func (c CpsController) Index(w http.ResponseWriter, r *http.Request)  {
	cpsData,pageData,err := cps.GetAll(r,10)
	if err != nil {
		c.ResposeForSQLError(w,err)
	} else {
		view.Render(w,view.D{
			"Cps": cpsData,
			"PagerData": pageData,
		},"cps.index")
	}
}

func (c CpsController) Create(w http.ResponseWriter, r *http.Request)  {
	channels,_ := channel.GetList()
	_cps := cps.Cps{}
	view.Render(w, view.D{
		"Channels": channels,
		"Cps": _cps,
	}, "cps.create", "cps._form_field")
}

func (c CpsController) Store(w http.ResponseWriter, r *http.Request)  {
	var errors map[string][]string
	_cps := cps.Cps{
		ChannelId: uint64(types.StringToInt(r.PostFormValue("channel_id"))),
		Title:     r.PostFormValue("title"),
		Tag:       r.PostFormValue("tag"),
		H5:        r.PostFormValue("h5"),
		AppId:     r.PostFormValue("appId"),
		Path:      r.PostFormValue("path"),
		Sort:      types.StringToInt(r.PostFormValue("sort")),
	}
	errors = requests.ValidateCpsForm(_cps)
	file, header, err := r.FormFile("logo")
	if err == nil {
		logo, errs := upload.UploadImage(file,header,"cps")
		if errs != nil {
			errors["logo"] = []string{errs.Error()}
		}
		_cps.Logo = logo
	}

	file2, header2, err2 := r.FormFile("image")
	if err2 == nil {
		image, errs2 := upload.UploadImage(file2,header2,"cps")
		if errs2 != nil {
			errors["image"] = []string{errs2.Error()}
		}
		_cps.Image = image
	}

	if len(errors) == 0 {
		// 创建文章
		_cps.Create()
		if _cps.ID > 0 {
			flash.Success("CPS创建成功")
			indexURL := route.Name2URL("cps.index")
			http.Redirect(w, r, indexURL, http.StatusFound)
		} else {
			flash.Danger("CPS创建失败")
			view.Render(w, view.D{
				"Cps": _cps,
				"Errors":  errors,
			}, "cps.create", "cps._form_field")
		}
	} else {
		channels,_ := channel.GetList()
		view.Render(w, view.D{
			"Cps": _cps,
			"Channels": channels,
			"Errors":  errors,
		}, "cps.create", "cps._form_field")
	}
}

func (c CpsController) Edit(w http.ResponseWriter, r *http.Request)  {
	id := route.GetRouteVariable("id", r)
	_cps , err := cps.Get(id)
	if err != nil {
		c.ResposeForSQLError(w, err)
	} else {
		channels,_ := channel.GetList()
		view.Render(w, view.D{
			"Cps": _cps,
			"Channels": channels,
			"Errors":  view.D{},
		}, "cps.edit", "cps._form_field")
	}
}

func (c CpsController) Update(w http.ResponseWriter, r *http.Request)  {
	id := route.GetRouteVariable("id", r)

	_cps,err := cps.Get(id)

	if err != nil {
		c.ResposeForSQLError(w,err)
	} else {
		var errors map[string][]string
		_cps.ChannelId = uint64(types.StringToInt(r.PostFormValue("channel_id")))
		_cps.Title =  r.PostFormValue("title")
		_cps.Tag =  r.PostFormValue("tag")
		_cps.H5 =  r.PostFormValue("h5")
		_cps.AppId =  r.PostFormValue("appId")
		_cps.Path =  r.PostFormValue("path")
		_cps.Sort =   types.StringToInt(r.PostFormValue("sort"))

		errors = requests.ValidateCpsForm(_cps)

		file, header, err := r.FormFile("logo")
		if err == nil {
			logo, errs := upload.UploadImage(file,header,"cps")
			if errs != nil {
				errors["logo"] = []string{errs.Error()}
			}
			_cps.Logo = logo
		}

		file2, header2, err2 := r.FormFile("image")
		if err2 == nil {
			image, errs2 := upload.UploadImage(file2,header2,"cps")
			if errs2 != nil {
				errors["image"] = []string{errs2.Error()}
			}
			_cps.Image = image
		}

		if len(errors) > 0 {
			channels,_ := channel.GetList()
			view.Render(w, view.D{
				"Cps": _cps,
				"Channels": channels,
				"Errors":  errors,
			}, "cps.edit", "cps._form_field")
		} else {
			rowsAffected, err := _cps.Update()
			if err != nil {
				flash.Danger("数据库错误，更改失败")
				showURL := route.Name2URL("cps.edit", "id", id)
				http.Redirect(w, r, showURL, http.StatusFound)
				return
			}
			if rowsAffected > 0 {
				flash.Success("更新成功")
				showURL := route.Name2URL("cps.edit", "id", id)
				http.Redirect(w, r, showURL, http.StatusFound)
			} else {
				flash.Danger("更新失败")
				showURL := route.Name2URL("cps.edit", "id", id)
				http.Redirect(w, r, showURL, http.StatusFound)
			}
		}
	}
}

func (c CpsController) Delete(w http.ResponseWriter, r *http.Request)  {
	id := route.GetRouteVariable("id",r)

	_cps , err := cps.Get(id)
	if err != nil {
		c.ResposeForSQLError(w,err)
	} else {
		rowsAffected, err := _cps.Delete()
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			fmt.Fprint(w, "500 服务器内部错误")
		} else {
			if rowsAffected > 0 {
				flash.Success("删除成功")
				indexURL := route.Name2URL("cps.index")
				http.Redirect(w, r, indexURL, http.StatusFound)
			} else {
				w.WriteHeader(http.StatusNotFound)
				fmt.Fprint(w, "404 CPS未找到")
			}
		}
	}
}